package com.wenhai.concurrency.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * {@link Unsafe} 示例
 *
 *
 * @ClassName UnsafeDemo
 * @Description
 * @Author 谢文海
 * @Date 2021/4/11 22:25
 * @Version 1.0
 * @see Unsafe
 **/
public class UnsafeDemo {
    private static final Unsafe UNSAFE;

    private static final long STATE_OFF_SET;

    private volatile long state = 0;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
            STATE_OFF_SET = UNSAFE.objectFieldOffset(UnsafeDemo.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }
    public static void main(String[] args) {
        UnsafeDemo unsafeDemo = new UnsafeDemo();
        System.out.println(UNSAFE.compareAndSwapInt(unsafeDemo, STATE_OFF_SET, 0, 2));
        System.out.println(unsafeDemo.state);
    }
}
